import { devConfig } from '../config.js';
import shell from 'shelljs';
import Client from 'ssh2-sftp-client';

import path from 'path';

import { fileURLToPath } from 'url';

const __filenameNew = fileURLToPath(import.meta.url);

const __dirnameNew = path.dirname(__filenameNew);
// 打包 npm run build
const compileDist = async () => {
    if (shell.exec('pnpm build:h5').code === 0) {
        console.log('打包成功');
    }
};

async function connectSSh() {
    const sftp = new Client();
    sftp.connect({
        host: devConfig.ip, // 服务器 IP
        port: devConfig.port,
        username: devConfig.username,
        password: devConfig.password,
    })
        .then(() => {
            console.log('先执行删除服务器文件');
            return sftp.rmdir(devConfig.rmpath, true);
        })
        .then(() => {
            // 上传文件
            console.log('删除成功，开始上传');
            return sftp.uploadDir(
                path.resolve(__dirnameNew, '../../dist/build/h5'),
                devConfig.path
            );
        })
        .then(() => {
            console.log('上传完成,开始拷贝至运行目录');
        })
        .catch(err => {
            console.log(err, '失败');
        })
        .finally(() => {
            sftp.end();
            console.log('部署成功');
        });
}
async function runTask() {
    await compileDist(); // 打包完成
    await connectSSh(); // 提交上传至个人目录
}
runTask();
